﻿using Arim.S4.Api;
using Arim.S4.Client.Base.Dto;
using System.Collections.Generic;
using System.Linq;
namespace Arim.S4.Client.Service
{
    public class ManufacturePlanAppService : BaseAppService<ManufacturePlanDto, ManufacturePlanQueryDto>
    {
        public ManufacturePlanAppService() : base(Urls.MANUFACTURE_PLAN.BASE) { }

        public IList<ManufacturePlanGroupDto> GetNotStartPlans()
        {
            var items = this.GetAll(new ManufacturePlanQueryDto() { CmdState = 15 });
            return items.GroupBy(s => new
            {
                Spec = s.Spec,
                SteelType = s.SteelType,
            }).Select(s => new ManufacturePlanGroupDto()
            {
                Spec = s.Key.Spec,
                SteelType = s.Key.SteelType,
                Count = s.Count(),
                Items = s.ToList()
            }).ToList();
        }

        /// <summary>
        /// 下达编制，下达后服务端会将制造命令由15置为16，并同时启动智能调度模型。客户端在此函数调用后，需用定时器重复调用 JobPlanAppService的 First()方法，直到有结果返回为止。
        /// </summary>
        public void Confirm(IList<ManufacturePlanGroupDto> group)
        {
            var updated = new List<ManufacturePlanStateChangedDto>(2);
            foreach (var item in group)
            {
                if (item.ConfirmCount == 0)
                    continue;

                updated.AddRange(item.Items.OrderBy(s => s.PlanDate).Take(item.ConfirmCount)
                 .Select(s => new ManufacturePlanStateChangedDto()
                 {
                     CmdNo = s.CmdNo,
                     CmdState = 16,
                 }));
            }
            this.BuildRestApi<ManufacturePlanStateChangedDto>().Post(Urls.MANUFACTURE_PLAN.CONFIRM, updated);
        }
    }

}
